package gui;

import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import javax.swing.JLabel;

import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.packet.Presence;

public class Buddy extends JLabel {
	private static final long serialVersionUID = 1L;
	private RosterEntry _entry;
	private Presence _presence;

	public Buddy(RosterEntry entry) {
		super();
		this.setOpaque(true); // JLabel's opacity is false by default
		

		_entry = entry;
		if (entry.getName() != null) {
			this.setText(entry.getName());
		} else {
			this.setText(entry.getUser());
		}
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);

		Color lines = Color.BLACK, fill = this.getBackground();
		String presence = "";

		Graphics2D g2d = (Graphics2D) g.create();
		FontMetrics fontMetrics = g2d.getFontMetrics();
		int nameWidth = fontMetrics.stringWidth(this.getText());
		if (_presence != null) {
			switch (_presence.getType()) {
			case available:
				if (_presence.getMode() != null) {
					switch (_presence.getMode()) {
					case available:
						lines = Color.GREEN;
						fill = Color.GREEN;
						presence = "available";
						break;
					case chat:
						lines = Color.BLACK;
						fill = Color.GREEN;
						presence = "chat";
						break;
					case dnd:
						lines = Color.YELLOW;
						fill = Color.YELLOW;
						presence = "dnd";
						break;
					case xa:
						lines = Color.BLACK;
						fill = Color.RED;
						presence = "xa";
						break;
					case away:
						lines = Color.ORANGE;
						fill = Color.ORANGE;
						presence = "away";
						break;
					default:
						lines = Color.BLACK;
						fill = this.getBackground();
						presence = "default";
						break;
					}
				} else {
					lines = Color.GREEN;
					fill = Color.GREEN;
					presence = "available (mode == null)";
				}
				break;
			case unavailable:
				lines = Color.RED;
				fill = Color.RED;
				presence = "unavailable";
				break;
			default:
				lines = Color.BLACK;
				fill = this.getBackground();
				presence = "unknown";
				break;
			}
		}

		g2d.drawString(presence, nameWidth + 10 + fontMetrics.getMaxAscent(),
				fontMetrics.getMaxAscent());

		g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
				RenderingHints.VALUE_ANTIALIAS_ON);
		g2d.setPaint(fill);
		g2d.fillOval(nameWidth + 5, 0, fontMetrics.getMaxAscent(), fontMetrics
				.getMaxAscent());
		g2d.setPaint(lines);
		g2d.drawOval(nameWidth + 5, 0, fontMetrics.getMaxAscent(), fontMetrics
				.getMaxAscent());
	}

	public RosterEntry getEntry() {
		return _entry;
	}

	public Presence getPresence() {
		return _presence;
	}

	public void setPresence(Presence _presence) {
		this._presence = _presence;
	}

}
